from django.shortcuts import render, redirect, HttpResponse
from web import models
from web.forms.project import ProjectModelForm
from django.http import JsonResponse


def project_list(request):

    """项目列表"""
    if request.method == 'GET':
        # get请求查看项目列表
        """
        ①：查找我创建的项目：已星标，未星标
            查找我参与的项目：已星标，未星标
        ②：提取已星标
            列表=循环[我创建的项目]+[我参与的项目]提取已星标的
        """
        project_dict = {'start': [], 'my': [], 'join': []}
        my_project_list = models.Project.objects.filter(creator=request.tracer.user)
        for row in my_project_list:
            if row.star:
                project_dict['start'].append({'value':row, 'type':'my'})
            else:
                project_dict['my'].append(row)

        join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)
        for item in join_project_list:
            if item.star:
                project_dict['start'].append({'value':item.project, 'type':'join'})
            else:
                project_dict['join'].append(item.project)

        form = ProjectModelForm(request)
        return render(request, 'project_list.html', {'form': form, 'project_dict':project_dict})

    form = ProjectModelForm(request, data=request.POST)
    if form.is_valid():
        # 验证通过 后加上 是谁创建了项目（creator）
        form.instance.creator = request.tracer.user
        # 创建项目
        form.save()
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def project_star(request,project_type, project_id):
    """星标"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
        return redirect('/project/list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=True)
        return redirect('/project/list')

    return HttpResponse('请求错误')

def project_unstar(request,project_type, project_id):
    """星标"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
        return redirect('/project/list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=False)
        return redirect('/project/list')

    return HttpResponse('请求错误')